#! /bin/sh

set -e

if [ -z "$1" -o -z "$2" ]; then
    echo "usage: $0 <listname> <srcdir> [src...]"
    exit 1
fi

list_name=$1
src_dir=$2
shift 2

list_modules()
{
    for src in $@; do
        src="$src_dir/$src"
        list=`sed -rn -e 's/^\s*MODULE_LUA_(BINDING|REGISTER)\((.*)\)\s*$/\2/p' "$src"`
        for mod in $list; do
            echo $mod
        done
    done
}

# some shells don't support `set -e -o pipefail'
list=`list_modules $@`
list=`echo $list | sort`

if [ -z "$list" ]; then
    echo "$list_name: initializer list is empty!" 1>&2
    exit 1
fi

echo '/* initializer prototypes */'
for mod in $list; do
    echo "MODULE_LUA_BINDING($mod);"
done
echo

echo '/* list of pointers to init functions */'
echo -n "#define $list_name"
for mod in $list; do
    echo ' \'
    echo -n "    luaopen_${mod},"
done
echo
